<template>
    <u-popup :show="show" @close="close" mode="bottom" :round="10" :closeable="false">
        <view @touchmove.prevent.stop class="popup-common ">
            <view class="title ">{{ nowPaymenthds?.classifyName }}</view>

            <scroll-view scroll-y="true" class="h-[70vh]  ">
                <view class="commission-bg sidebar-margin my-[var(--top-m)] rounded-[var(--rounded-big)] py-[30rpx]">

                    <view class="flex justify-around commission-content" v-if="nowPaymenthds.classify == 'change'">
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">零售总价(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(prcieCount
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">总计优惠(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(discountPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">实售总价(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(payPrice
                                ) }}</text>
                        </view>
                    </view>
                    <view class="flex justify-around commission-content" v-if="nowPaymenthds.classify == 'debt'">
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">实售总价(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(selectedSku.realPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">欠款金额(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(formData.arrearsPrice
                                ) }}</text>
                        </view>
                        <view class="flex flex-col items-center">
                            <text class="text-[30rpx] text-[var(--text-color-light9)]">实售总价(元)</text>
                            <text class="text-[#303133] price-font text-[38rpx] font-500 mt-[16rpx]">{{
                                fen2yuan(payPrice
                                ) }}</text>
                        </view>
                    </view>
                </view>
                <view class="card-template mt-[30rpx]" v-if="nowPaymenthds.classify == 'debt'">
                    <view class="font-500 text-[34rpx] text-[#333] leading-[42rpx]">欠款金额
                    </view>
                    <view
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <text class="pt-[4rpx] text-[40rpx] text-[#333] iconfont iconrenminbiV6xx price-font "></text>
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 price-font text-[44rpx] bg-[#fff]"
                            v-model="nowPayment.usePayBalance" maxlength="7" :placeholder="'请输入欠款金额'"
                            placeholder-class="apply-price" :adjust-position="false" />
                        <text @click="onHandleCancel" v-if="nowPayment.usePayBalance"
                            class="nc-iconfont nc-icon-cuohaoV6xx1 !text-[44rpx] text-[var(--text-color-light9)]"></text>
                    </view>
                    <view class="pt-[16rpx] flex items-center justify-between px-[4rpx]">
                        <view class="text-[34rpx] text-[var(--text-color-light6)] price-font leading-[36rpx]">
                            <!-- <text>最低限价：￥{{ fen2yuan(state.orderInfo.price.lowerPrice) }}</text> -->
                        </view>
                        <view class="text-[34rpx] text-primary leading-[36rpx]" @click="onHandleCancel()">取消欠款
                        </view>
                    </view>
                </view>
                <view class="card-template mt-[30rpx]" v-if="nowPaymenthds.classify == 'change'">
                    <view class="font-500 text-[34rpx] text-[#333] leading-[42rpx]">优惠后商品金额
                    </view>
                    <view
                        class="flex pt-[30rpx] pb-[8rpx] items-center border-0 border-b-[2rpx] border-solid border-[#F1F2F5]">
                        <text class="pt-[4rpx] text-[40rpx] text-[#333] iconfont iconrenminbiV6xx price-font "></text>
                        <input type="digit"
                            class="h-[76rpx] leading-[76rpx] pl-[10rpx] flex-1 font-500 price-font text-[44rpx] bg-[#fff]"
                            v-model="nowPayment.usePayBalance" maxlength="7" :placeholder="formData.distType == 0
                                ? '请输入优惠后商品总价'
                                : formData.distType == 1
                                    ? '请输入商品折扣(1-100)'
                                    : ''" placeholder-class="apply-price" :adjust-position="false" />
                        <text @click="clearMoney" v-if="nowPayment.usePayBalance"
                            class="nc-iconfont nc-icon-cuohaoV6xx1 !text-[44rpx] text-[var(--text-color-light9)]"></text>
                    </view>
                    <view class="pt-[16rpx] flex items-center justify-between px-[4rpx]">
                        <view class="text-[34rpx] text-[var(--text-color-light6)] price-font leading-[36rpx]">
                            <text>最低限价：￥{{ fen2yuan(selectedSku.lowerPrice) }}</text>
                        </view>
                        <view class="text-[34rpx] text-primary leading-[36rpx]" @click="onHandleCancel()">取消优惠
                        </view>
                    </view>
                </view>

            </scroll-view>
            <!-- <u-keyboard mode="number" @change="valChange" @backspace="backspace" :overlay="false" :showTips="false"
                :tooltip="false" safeAreaInsetBottom :show="show" class="keyboard-common">
            </u-keyboard> -->
            <view class="btn-wrap">
                <button class="primary-btn-bg btn" @click="confirm">确认</button>
            </view>
        </view>
    </u-popup>
</template>
<script setup lang="ts">
import { ref, watch, computed, reactive, unref } from 'vue'
import { fen2yuan, yuan2fen } from '@/utils/formatting';
import { cloneDeep } from 'lodash-es'

const props = defineProps({
    orderInfo: {
        type: Object,
        default: () => {
            return {

            }
        }
    }, //订单信息
    paymentMap: {
        type: Array,
        default: () => {
            return []
        }
    }
})

const nowPaymenthds = ref() //当前使用的资产
const state = reactive({
    orderInfo: computed(() => {
        return props.orderInfo
    }), // 支付单信息
    payMethods: computed(() => {
        return props.paymentMap.find((ele: any) => {
            return ele.classify == nowPaymenthds.value.classify
        })
    }) as any, // 可选的支付方式
    payment: '', // 选中的支付方式
    payOrderList: [] as any, //当前支付方式的支付流水号
    activeName: '', //当前选中的支付方式
})

const formData = ref({
    id: undefined, // 订单编号
    arrearsPrice: '' as any, // 欠款金额
    distType: 0, //优惠类型
    distPrice: '' as any, //优惠值
    payPrice: '' as any // 调价后应付金额(总)
})
// const discountTypeOptions = computed(() => {
//     return [
//         {
//             label: '总价',
//             value: 0
//         },
//         {
//             label: '折扣',
//             value: 1
//         }
//     ]
// })
const payPrice = computed(() => {
    if (formData.value.distPrice > 0) {
        return formData.value.payPrice
    } else {
        return selectedSku.value.realPrice
    }
}) //前端计算的实售总价
const prcieCount = computed(() => {
    return selectedSku.value.price * selectedSku.value.count
}) //零售总价
const discountPrice = computed(() => {
    let discount = prcieCount.value - payPrice.value
    return discount > 0 ? discount : 0
}) //优惠金额
const nowPayment = ref<any>({})
const nowPaymentIndex = ref<any>() //当前支付方式的下标
// 监听支付方式的变化
// watch(
//     () => props.paymentMap,
//     () => {
//         if (nowPaymentIndex.value == undefined) {
//             return
//         }

//         nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
//         if (nowPayment.value.payStatus) {
//             nowPayment.value.usePayBalance = fen2yuan(nowPayment.value.paybalance)
//         } else {
//             nowPayment.value.usePayBalance = ''
//         }
//     }
// )

const show = ref(false)
const emits = defineEmits(['confirm'])
// const valChange = (val: any) => {

//     nowPayment.value.usePayBalance += val;

// };

// const backspace = () => {
//     // 删除value的最后一个字符
//     if (nowPayment.value.usePayBalance.length) {
//         nowPayment.value.usePayBalance = nowPayment.value.usePayBalance.substr(0, nowPayment.value.usePayBalance.length - 1);
//     }
// };
// 清空提现金额
const clearMoney = () => {
    nowPayment.value.usePayBalance = '';
}





const close = () => {
    show.value = false


}
const selectPayMent = (index: any) => {
    nowPaymentIndex.value = index
    let item = state.payMethods.items[nowPaymentIndex.value]
    nowPayment.value = item
    if (item.payStatus) {
        nowPayment.value.usePayBalance = fen2yuan(nowPayment.value.paybalance)
    } else {
        nowPayment.value.usePayBalance = ''
    }
}

const selectedSku = ref()
const open = (sku: any, payMethods: any) => {

    selectedSku.value = sku
    formData.value.id = sku.cartId!
    formData.value.arrearsPrice = Number(sku.arrearsPrice!)
    formData.value.distType = sku.distType || 0

    nowPaymenthds.value = payMethods
    nowPayment.value = payMethods
    if (nowPayment.value.classify == 'debt') {
        nowPayment.value.usePayBalance = selectedSku.value.arrearsPrice ? fen2yuan(selectedSku.value.arrearsPrice) : ''
    } else {
        if (formData.value.distType == 0) {
            nowPayment.value.usePayBalance = selectedSku.value.distPrice ? fen2yuan(selectedSku.value.distPrice) : ''
        }
        if (formData.value.distType == 1) {
            nowPayment.value.usePayBalance = formData.value.distPrice
        }
        countPayPrice()
    }
    show.value = true

    // setNowPayment()

}



/** 校验欠款 */
const testArrears = () => {
    if (nowPayment.value.usePayBalance) {
        // 判断优惠价 是否低于最低价
        formData.value.arrearsPrice = yuan2fen(nowPayment.value.usePayBalance)
        if (Number(formData.value.arrearsPrice) > Number(selectedSku.value.realPrice)) {
            uni.showToast({
                title: '欠款金额不得高于实售总价',
                icon: 'none'
            })
            return false
        } else {
            return true
        }
    } else {
        return false
    }
}
const countPayPrice = () => {
    console.log(nowPayment.value.usePayBalance)
    console.log(formData.value.distType)

    if (formData.value.distType == 0) {
        formData.value.distPrice = yuan2fen(nowPayment.value.usePayBalance)

        formData.value.payPrice = formData.value.distPrice
    } else if (formData.value.distType == 1) {
        formData.value.distPrice = nowPayment.value.usePayBalance

        formData.value.payPrice =
            Number(selectedSku.value.realPrice || 0) * (Number(formData.value.distPrice) / 100)
    } else {
        return 0
    }
}
const testDiscount = () => {
    if (nowPayment.value.usePayBalance) {


        countPayPrice()

        // 判断优惠价 是否低于最低价

        if (Number(selectedSku.value.lowerPrice) > Number(formData.value.payPrice)) {
            uni.showToast({
                title: '优惠价不得低于最低限价',
                icon: 'none'
            })
            return false
        } else {
            return true
        }
    } else {
        return false
    }
}
const confirm = () => {
    if (nowPayment.value.classify == 'debt') {
        const testArrearsStatus = testArrears()
        if (testArrearsStatus) {
            submitDebtPrice()
        } else {
        }
    }
    if (nowPayment.value.classify == 'change') {
        const testUpdatePriceStatus = testDiscount()
        if (testUpdatePriceStatus) {
            submitUpdatePrice()
        } else {
        }
    }


}

const formLoading = ref()
const submitUpdatePrice = async () => {
    // 提交请求
    formLoading.value = true
    try {
        const data = cloneDeep(unref(formData))

        data.type = 'updatePrice'


        // 发送操作成功的事件
        emits('confirm', data)

        close()
    } finally {
        formLoading.value = false
    }
}
const submitDebtPrice = async () => {
    // 提交请求
    formLoading.value = true
    try {
        const data = cloneDeep(unref(formData))
        data.type = 'debtPrice'

        // await shopCartStore.updateCart({
        //     id: data.id,
        //     count: selectedSku.value.count,
        //     arrearsPrice: data.arrearsPrice
        // })
        // dialogVisible.value = false
        // message.success('设置成功')

        // // 发送操作成功的事件
        // emit('success', true)
        emits('confirm', data)
        close()


    } finally {
        formLoading.value = false
    }
}
const onHandleCancel = () => {
    if (nowPayment.value.classify == 'debt') {
        formData.value.arrearsPrice = 0
        submitDebtPrice()

    }
    if (nowPayment.value.classify == 'change') {
        formData.value.distPrice = 0
        formData.value.distType = 0
        submitUpdatePrice()
    }
}

defineExpose({
    open,

})
</script>
<script lang="ts">
export default {
    options: {
        styleIsolation: 'shared'
    }
}  
</script>
<style lang="scss" scoped>
:deep(.apply-price) {
    color: var(--text-color-light9);
    font-size: 34rpx;
    font-weight: normal;
    line-height: 76rpx;
}

.popup-common .title {
    font-weight: 500;
    text-align: center;
    font-size: 1.125rem;
    padding-top: 1.125rem;
    line-height: 1;
    padding-bottom: 0;
}

.commission-bg {
    background: #f6f6f6;
}

.commission-content>view {
    position: relative;
    width: 6.5625rem
}

.commission-content>view:after {
    content: "";
    position: absolute;
    width: .0625rem;
    height: 1.875rem;
    background-color: var(--temp-bg);
    top: 50%;
    right: 0;
    transform: translateY(-50%)
}

.commission-content>view:last-of-type:after {
    width: 0;
    height: 0
}
</style>